/*
 *  Copyright (c) 2018-2020, baomidou (63976799@qq.com).
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.baomidou.lock.executor;

import com.baomidou.lock.annotation.Lock4j;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zengzhihong Succy
 */
@Slf4j
public class LockExecutorFactory {

    /**
     * 构造执行器。优化之后不再使用显式注入方式注入Redis客户端或ZK客户端，通过运行时从
     * ApplicationContext获取对应的Bean，如果没有引入对应的jar，在执行具体上锁的时候
     * 可能发送NPE。这与之前的思路无差异，注入的话如果没有对应的bean同样会发生NPE，显式
     * 的字段注入还会在没引入依赖时，启动报ClassNotFoundException。
     * <p>
     * 正常情况下，调用本方法是通过LockTemplate的lock方法调用，这个时候IOC肯定是加载完成
     * 则在new具体的LockExecutor实现类时，根据对应的client参数一定可以从ApplicationContext
     * 中获取到对应client的Bean的
     */
    public LockExecutor buildExecutor(Lock4j lock4j) {

        switch (lock4j.client()) {
            case ZOOKEEPER:
                return new ZookeeperLockExecutor();
            case REDIS_TEMPLATE:
                return new RedisTemplateLockExecutor();
            case REDISSON:
                switch (lock4j.type()) {
                    case REENTRANT:
                        return new RedissonReentrantLockExecutor();
                    case READ:
                        return new RedissonReadLockExecutor();
                    case WRITE:
                        return new RedissonWriteLockExecutor();
                    case Fair:
                        return new RedissonFairLockExecutor();
                    default:
                        throw new IllegalArgumentException("error lock4j type argument");
                }
            default:
                throw new IllegalArgumentException("error lock4j client argument");
        }
    }
}
